package com.qianbei.common.view;

import android.content.Context;
import android.text.Layout;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * Created by user on 16/11/1.
 */

public class CustomReadTextView extends TextView {

    private CharSequence mEndText;

    private StringBuilder builder = new StringBuilder();

    public CustomReadTextView(Context context) {
        super(context);
    }

    public CustomReadTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        resize();
    }

    /**
     * 去除当前页无法显示的字
     * @return 去掉的字数
     */
    public int resize() {

        int lineNumber = getCharNum();

        int line = getLineCount();
        CharSequence newContent = "";
        CharSequence oldContent = getText();

        builder.replace(0,builder.length(),"");

        if (line >=2){
             newContent = oldContent.subSequence(0, lineNumber);

            if (!TextUtils.isEmpty(mEndText)) {
                newContent = newContent.subSequence(0, newContent.length() - mEndText.length());
                builder.append(newContent).append(" ").append(mEndText);
            }else {
                builder.append(newContent);
            }
        }else{
            if (TextUtils.isEmpty(mEndText)){
                builder.append(oldContent);
            }else{
                builder.append(oldContent).append(" ").append(mEndText);
            }

        }

        setText(builder);


        return oldContent.length() - newContent.length();
    }

    /**
     * 获取当前页总字数
     */
    public int getCharNum() {
        return getLayout().getLineEnd(getLineNum());
    }

    /**
     * 获取当前页总行数
     */
    public int getLineNum() {
        Layout layout = getLayout();
        int topOfLastLine = getHeight() - getPaddingTop() - getPaddingBottom() - getLineHeight();
        return layout.getLineForVertical(topOfLastLine);
    }

    public void setEndText(CharSequence endText){
        mEndText = endText;
    }

}
